package com.whz.gateway.common.util;

import lombok.experimental.UtilityClass;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

/**
 * @author whz
 */
@UtilityClass
public class PathMatcherUtils {
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    /**
     * 路径path是否匹配 pattern
     *
     * @param pattern 模板
     * @param path    当前路径
     * @return true 匹配
     */
    public static boolean match(final String pattern, final String path) {
        // 以'/'结尾的删除
        String purePath = StringUtils.trimWhitespace(path);
        while (purePath.endsWith(AntPathMatcher.DEFAULT_PATH_SEPARATOR)) {
            purePath = purePath.substring(0, purePath.length() - 1);
        }
        return ANT_PATH_MATCHER.match(pattern, purePath);
    }

    /**
     * 批量匹配
     *
     * @param path     访问路径
     * @param patterns 匹配模板
     * @return true 匹配成功
     */
    public static boolean matchs(String path, String... patterns) {
        if (patterns != null) {
            for (String p : patterns) {
                if (match(p, path)) {
                    return true;
                }
            }
        }
        return false;
    }
}